package alibaba.shared;

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class Utils {
	/* Constants */
	public static final String SIGNATURE_QUERY_STR = "signature";
	public static final String CHECK_QUERY_STR = "check";
	public static final String AUTHORIZATION_STR = "Authorization";

	public static final String SERVER_PRINTING_PREFIX = "AlibabaServer: ";
	public static final String CLIENT_PRINTING_PREFIX = "AlibabaClient: ";

	private static final int BUFFER_SIZE = 4096;

	public static byte[] getDataHash(byte[] data) {
		MessageDigest md;
		try {
			md = MessageDigest.getInstance("SHA-256");
		} catch (NoSuchAlgorithmException e) {
			// Don't worry... There is such algorithm :).
			e.printStackTrace();
			return null;
		}
		md.reset();
		md.update(data);
		return md.digest();
	}

	public static byte[] getFileHash(File file) throws IOException {
		return getDataHash(readFileIntoBuf(file));
	}

	public static byte[] readFileIntoBuf(File file) throws IOException {
		BufferedInputStream in = new BufferedInputStream(new FileInputStream(file));
		int fileLength = (int) file.length();
		byte[] buf = new byte[fileLength];
		int read = 0;
		int pos = 0;
		while ((read = in.read(buf, pos, fileLength - pos)) != 0) {
			pos += read;
		}
		return buf;
	}

	/**
	 * Reads the full stream (until EOF) to a byte[].
	 *
	 * NOTE: You should always use readFileIntBuf for files.
	 *
	 * @param stream
	 *            the stream to read
	 * @return byte[] of the stream.
	 * @throws IOException
	 */
	public static byte[] readInputIntoBuf(InputStream stream) throws IOException {
		BufferedInputStream bis = new BufferedInputStream(stream);
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		byte[] buf = new byte[BUFFER_SIZE];
		int read = 0;
		while ((read = bis.read(buf)) != -1) {
			baos.write(buf, 0, read);
		}
		return baos.toByteArray();
	}
}
